const ncname = `[a-zA-Z_][\\-\\.0-9_a-zA-Z]*`
const qnameCapture = `((?:${ncname}\\:)?${ncname})`
const startTagOpen = new RegExp(`^<${qnameCapture}`)
const endTag = new RegExp(`^<\\/${qnameCapture}[^>]*>`)
const attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/
const startTagClose = /^\s*(\/?)>/
const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g

function parseText() {}
function parseElement() {}


function delStr(raw:string, len:number) {
  return raw.substring(len)
}

function handle(type:'startTag'|'text'|'closeTag', args:any) {
  switch(type) {
    case 'startTag':
      break
    case 'text':
      break
    case 'closeTag':
      break    
  }
}

function parseStartTag(html:string) {
  const matchResult = html.match(startTagOpen)!
  const delSize = matchResult[0].length
  const vnode = {
    tag: matchResult[1],
    props:{},
    children:[]
  }

  html = delStr(html, delSize)

  let attrsMatch: RegExpMatchArray|null = null
  let tagCloseMatch: RegExpMatchArray|null = null

  while(!(tagCloseMatch=html.match(startTagClose)) && (attrsMatch=html.match(attribute))) {
    const [matchContent, name, , value] = attrsMatch
    
    // @ts-ignore
    vnode.props[name] = value

    html = delStr(html, matchContent.length)
  }

  handle('startTag', vnode)

  if(tagCloseMatch) html = delStr(html, tagCloseMatch[0].length)

  return html
}

export function parsehtml(html:string) {
  while(html) {
    const pos = html.indexOf('<')
    if(pos === 0) {
      if(html.match(startTagOpen)) {
        html = parseStartTag(html)
      }

      const matchResult = html.match(endTag)

      if(matchResult) {
        handle('closeTag', matchResult[1])
        html = delStr(html, matchResult[0].length)
      }

    } else if(pos > 0) {
      const text = html.slice(0, pos)
      handle('text', text)
      html = delStr(html, text.length)
    }
  }

  return {
    tag:'div',
    props:{
      id:'',
      style:'color:red; font-size:18px;',
      class:''
    },
    children:[
      'hello, {{ name }}',
      '_^_',
      {
        tag:'p',
        props:{},
        children:[]
      }
    ]
  }
}
